<?php

namespace app\api\controller;

use app\common\controller\Api;
use \app\common\model;
use app\common\model\BehaviorCategory;
use app\common\model\BehaviorRecord;

/**
 * 排行榜
 */
class Ranking extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['student', 'dorm', 'classes', 'records'];

    /**
     * @ApiTitle    (学生排行榜)
     * @ApiAuthor   (Zhenzh)
     * @ApiDate     (2020/2/12)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/ranking/student)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiParams   (name="school_id", type="int", required=true, description="学校 id", sample="")
     * @ApiParams   (name="keywords", type="string", required=false, description="搜索关键词", sample="")
     * @ApiParams   (name="date_type", type="string", required=true, description="日期搜索 1今天 2昨天 3本周「默认」 4上周 5近7天 6本月 7上月 8近30天 9本季度 10上季度 11本年 12上年", sample="")
     * @ApiParams   (name="page", type="int", required=false, description="页码", sample="")
     * @ApiParams   (name="listRows", type="int", required=false, description="每页条数 默认 10", sample="")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ({
    "code": 1,
    "msg": "",
    "time": "1581573221",
    "data": {
    "total": 1,
    "per_page": 10,
    "current_page": 1,
    "last_page": 1,
    "data": [
    {
    "student_id": 2369,
    "score": "3",
    "sort": 1
    }
    ]
    }
    })
     */
    public function student()
    {
        $school_id = $this->request->request('school_id');
        if (!$school_id) {
            $this->error('参数错误');
        }

        $listRows = $this->request->request('listRows', 10);
        $date_type = $this->request->request('date_type', 3);
        $keywords = $this->request->request('keywords', '');

        $search_students = [];
        // 如果有 $keywords 先搜索出 student 信息
        if ($keywords) {
            $search_students = \app\common\model\Student::alias('student')
                ->join('__CLASSES__ classes', 'classes.id = student.class_id')
                ->join('__GRADE__ grade', 'grade.id = student.grade_id')
                ->join('__TEACHER__ teacher', 'teacher.id = classes.headmaster', 'left')
                ->join('__USER__ user', 'user.id = teacher.user_id', 'left')
                ->where('student.school_id', $school_id)
                ->whereLike('student.name|student.number', "%$keywords%")
                ->field('student.*,classes.name class_name,grade.name grade_name,classes.headmaster headmaster_id,user.nickname headmaster_name')
                ->column('student.*,classes.name class_name,grade.name grade_name,classes.headmaster headmaster_id,user.nickname headmaster_name', 'student.id');
            foreach ($search_students as $key => $value) {
                if (!strstr($value['avatar'], 'http') && strstr($value['avatar'], '/uploads/')) {
                    $search_students[$key]['avatar'] = config('mp.url') . $value['avatar'];
                }
            }
        }

        if ($keywords && !$search_students) {
            $this->success('');
        }

        $date = get_time($date_type, true);

        $result = model\BehaviorRecord::alias('record')
            ->join('__BEHAVIOR_RECORD_DETAIL__ detail', 'detail.record_id = record.id')
            ->where('record.school_id', $school_id)
            ->where('record.created_at', '>=', $date['start_time'])
            ->where('record.created_at', '<=', $date['end_time'])
            ->whereIn('record.behavior_category_type', [model\BehaviorCategory::STUDENT, model\BehaviorCategory::DORM])
            ->whereIn('detail.behavior_category_type', [model\BehaviorCategory::STUDENT, model\BehaviorCategory::DORM_STUDENT])
            ->where('detail.student_id', '>', 0)
            ->where(function ($query) use ($search_students) {
                if ($search_students) {
                    $query->whereIn('detail.student_id', array_keys($search_students));
                }
            })
            ->field('detail.student_id,sum(detail.score) score,record.json_data')
            ->group('detail.student_id')
            ->order('score', 'desc')
            ->paginate($listRows);

        if ($result) {

            if (!is_array($result)) $result = $result->toArray();

            if (isset($result['data']) && $result['data']) {

                if ($search_students) {
                    foreach ($result['data'] as $key => $value) {
                        if (isset($search_students[$value['student_id']])) {
                            $result['data'][$key] = array_merge($result['data'][$key], $search_students[$value['student_id']]);
                        } else if ($value['json_data']) {
                            $result['data'][$key] = array_merge($result['data'][$key], $value['json_data']);
                        }
                        unset($result['data'][$key]['json_data']);
                        $count = model\BehaviorRecord::alias('record')
                            ->join('__BEHAVIOR_RECORD_DETAIL__ detail', 'detail.record_id = record.id')
                            ->where('record.school_id', $school_id)
                            ->where('record.created_at', '>=', $date['start_time'])
                            ->where('record.created_at', '<=', $date['end_time'])
                            ->whereIn('record.behavior_category_type', [model\BehaviorCategory::STUDENT, model\BehaviorCategory::DORM])
                            ->whereIn('detail.behavior_category_type', [model\BehaviorCategory::STUDENT, model\BehaviorCategory::DORM_STUDENT])
                            ->where('detail.student_id', '>', 0)
                            ->group('detail.student_id')
                            ->having('sum(score) > ' . $value['score'])
                            ->count();
                        $result['data'][$key]['sort'] = $count + 1;
                    }
                } else {
                    $student_ids = array_column($result['data'], 'student_id');
                    $students = \app\common\model\Student::alias('student')
                        ->join('__CLASSES__ classes', 'classes.id = student.class_id')
                        ->join('__GRADE__ grade', 'grade.id = student.grade_id')
                        ->join('__SCHOOL__ school', 'school.id = student.school_id')
                        ->join('__TEACHER__ teacher', 'teacher.id = classes.headmaster', 'left')
                        ->join('__USER__ user', 'user.id = teacher.user_id', 'left')
                        ->whereIn('student.id', $student_ids)
                        ->field('student.*,classes.name class_name,grade.name grade_name,classes.headmaster headmaster_id,user.nickname headmaster_name')
                        ->column('student.*,school.name school_name,classes.name class_name,grade.name grade_name,classes.headmaster headmaster_id,user.nickname headmaster_name', 'student.id');

                    foreach ($students as $key => $value) {
                        if (!strstr($value['avatar'], 'http') && strstr($value['avatar'], '/uploads/')) {
                            $students[$key]['avatar'] = config('mp.url') . $value['avatar'];
                        }
                    }

                    // 第一个是分数最大的
                    $max = current($result['data']);

                    // 获取比当前最大分分数高的人数
                    $count = model\BehaviorRecord::alias('record')
                        ->join('__BEHAVIOR_RECORD_DETAIL__ detail', 'detail.record_id = record.id')
                        ->where('record.school_id', $school_id)
                        ->where('record.created_at', '>=', $date['start_time'])
                        ->where('record.created_at', '<=', $date['end_time'])
                        ->whereIn('record.behavior_category_type', [model\BehaviorCategory::STUDENT, model\BehaviorCategory::DORM])
                        ->whereIn('detail.behavior_category_type', [model\BehaviorCategory::STUDENT, model\BehaviorCategory::DORM_STUDENT])
                        ->where('detail.student_id', '>', 0)
                        ->group('detail.student_id')
                        ->having('sum(score) > ' . $max['score'])
                        ->count();

                    foreach ($result['data'] as $key => $value) {
                        if (isset($students[$value['student_id']])) {
                            $result['data'][$key] = array_merge($result['data'][$key], $students[$value['student_id']]);
                        } else if ($value['json_data']) {
                            $result['data'][$key] = array_merge($result['data'][$key], $value['json_data']);
                        }
                        unset($result['data'][$key]['json_data']);

                        //数组中第一个是当前分数最高的 排名为$sort
                        if ($key == 0) {
                            $result['data'][$key]['sort'] = $count + $key + 1;
                        } else {
                            // 继续循环
                            // 如果当前的分数与上一个的相等 那么就与上一个的排名并列
                            if ($result['data'][$key - 1]['score'] == $value['score']) {
                                $result['data'][$key]['sort'] = $result['data'][$key - 1]['sort'];
                            } else {
                                // 如果不等 那就看看有没有分页情况
                                // 如果有分页 也就是说之前的所有的分数都大于当前的分数 排名累加上
                                $result['data'][$key]['sort'] = ($result['current_page'] - 1) * $listRows + $key + 1;
                            }
                        }
                    }
                }
            }
        }

        $this->success('', $result);

    }

    /**
     * @ApiTitle    (宿舍排行榜)
     * @ApiAuthor   (Zhenzh)
     * @ApiDate     (2020/2/13)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/ranking/dorm)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiParams   (name="school_id", type="int", required=true, description="学校 id", sample="")
     * @ApiParams   (name="keywords", type="string", required=false, description="搜索关键词", sample="")
     * @ApiParams   (name="date_type", type="string", required=true, description="日期搜索 1今天 2昨天 3本周「默认」 4上周 5近7天 6本月 7上月 8近30天 9本季度 10上季度 11本年 12上年", sample="")
     * @ApiParams   (name="page", type="int", required=false, description="页码", sample="")
     * @ApiParams   (name="listRows", type="int", required=false, description="每页条数 默认 10", sample="")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ()
     */
    public function dorm()
    {
        $school_id = $this->request->request('school_id');
        if (!$school_id) {
            $this->error('参数错误');
        }

        $listRows = $this->request->request('listRows', 10);
        $date_type = $this->request->request('date_type', 3);
        $keywords = $this->request->request('keywords', '');

        $search_dorms = [];
        // 如果有 $keywords 先搜索出 dorm 信息
        if ($keywords) {
            $search_dorms = model\Dorm::alias('a')
                ->where('a.school_id', $school_id)
                ->where('a.number|a.name', 'like', "%$keywords%")
                ->where('a.status', model\Dorm::NORMAL)
                ->column('a.id,a.garden_number,a.building_number,a.number,a.bed_count,a.bed_used_count');
        }

        if ($keywords && !$search_dorms) {
            $this->success('');
        }

        $date = get_time($date_type, true);

        $result = model\BehaviorRecord::alias('record')
            ->join('__BEHAVIOR_RECORD_DETAIL__ detail', 'detail.record_id = record.id')
            ->where('record.school_id', $school_id)
            ->where('record.dorm_id', '>', 0)
            ->where('record.behavior_category_type', model\BehaviorCategory::DORM)
            ->where('record.created_at', '>=', $date['start_time'])
            ->where('record.created_at', '<=', $date['end_time'])
            ->where(function ($query) use ($search_dorms) {
                if ($search_dorms) {
                    $query->whereIn('record.dorm_id', array_keys($search_dorms));
                }
            })
            ->field('record.dorm_id,record.json_data,sum(detail.score) score')
            ->group('record.dorm_id')
            ->order('score', 'desc')
            ->paginate($listRows);

        if ($result) {
            if (!is_array($result)) $result = $result->toArray();

            if (isset($result['data']) && $result['data']) {
                foreach ($result['data'] as $key => $value) {

                    $bed_count = \app\common\model\Bed::where('school_id', $value['json_data']['school_id'])
                        ->where('garden_number', $value['json_data']['garden_number'])
                        ->where('building_number',  $value['json_data']['building_number'])
                        ->where('dorm_number', $value['json_data']['dorm_number'])
                        ->where('status', \app\common\model\Bed::ZAIYONG)
                        ->count();

                    $result['data'][$key]['bed_used_count'] = $bed_count;
                }

                if ($search_dorms) {
                    foreach ($result['data'] as $key => $value) {
                        if ($value['json_data']) {
                            $result['data'][$key] = array_merge($result['data'][$key], $value['json_data']);
                        }
                        unset($result['data'][$key]['json_data']);
                        if (isset($search_dorms[$value['dorm_id']])) {
                            $result['data'][$key] = array_merge($result['data'][$key], $search_dorms[$value['dorm_id']]);
                        }
                        $count = model\BehaviorRecord::alias('record')
                            ->join('__BEHAVIOR_RECORD_DETAIL__ detail', 'detail.record_id = record.id')
                            ->where('record.school_id', $school_id)
                            ->where('record.dorm_id', '>', 0)
                            ->where('record.behavior_category_type', model\BehaviorCategory::DORM)
                            ->where('record.created_at', '>=', $date['start_time'])
                            ->where('record.created_at', '<=', $date['end_time'])
                            ->group('record.dorm_id')
                            ->having('sum(detail.score) > ' . $value['score'])
                            ->count();
                        $result['data'][$key]['sort'] = $count + 1;
                    }
                } else {
                    $dorm_ids = array_column($result['data'], 'dorm_id');
                    $dorms = model\Dorm::whereIn('id', $dorm_ids)
                        ->where('status', model\Dorm::NORMAL)
                        ->column('id,number,name,school_id,garden_number,building_number,bed_count', 'id');

                    // 第一个是分数最大的
                    $max = current($result['data']);
                    // 获取比当前最大分分数高的人数
                    $count = model\BehaviorRecord::alias('record')
                        ->join('__BEHAVIOR_RECORD_DETAIL__ detail', 'detail.record_id = record.id')
                        ->where('record.school_id', $school_id)
                        ->where('record.dorm_id', '>', 0)
                        ->where('record.behavior_category_type', model\BehaviorCategory::DORM)
                        ->where('created_at', '>=', $date['start_time'])
                        ->where('created_at', '<=', $date['end_time'])
                        ->group('record.dorm_id')
                        ->having('sum(detail.score) > ' . $max['score'])
                        ->count();

                    foreach ($result['data'] as $key => $value) {

                        if ($value['json_data']) {
                            $result['data'][$key] = array_merge($result['data'][$key], $value['json_data']);
                        }
                        unset($result['data'][$key]['json_data']);

                        if (isset($dorms[$value['dorm_id']])) {
                            $result['data'][$key]['bed_count'] = $dorms[$value['dorm_id']]['bed_count'];
                            //$result['data'][$key]['bed_used_count'] = $dorms[$value['dorm_id']]['bed_used_count'];
                        }

                        //数组中第一个是当前分数最高的 排名为$sort
                        if ($key == 0) {
                            $result['data'][$key]['sort'] = $count + $key + 1;
                        } else {
                            // 继续循环
                            // 如果当前的分数与上一个的相等 那么就与上一个的排名并列
                            if ($result['data'][$key - 1]['score'] == $value['score']) {
                                $result['data'][$key]['sort'] = $result['data'][$key - 1]['sort'];
                            } else {
                                // 如果不等 那就看看有没有分页情况
                                // 如果有分页 也就是说之前的所有的分数都大于当前的分数 排名累加上
                                $result['data'][$key]['sort'] = ($result['current_page'] - 1) * $listRows + $key + 1;
                            }
                        }
                    }
                }

            }
        }
        $this->success('', $result);
    }

    /**
     * @ApiTitle    (班级排行榜)
     * @ApiAuthor   (Zhenzh)
     * @ApiDate     (2020/2/12)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/ranking/classes)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiParams   (name="school_id", type="int", required=true, description="学校 id", sample="")
     * @ApiParams   (name="keywords", type="string", required=false, description="搜索关键词", sample="")
     * @ApiParams   (name="date_type", type="string", required=true, description="日期搜索 1今天 2昨天 3本周「默认」 4上周 5近7天 6本月 7上月 8近30天 9本季度 10上季度 11本年 12上年", sample="")
     * @ApiParams   (name="page", type="int", required=false, description="页码", sample="")
     * @ApiParams   (name="listRows", type="int", required=false, description="每页条数 默认 10", sample="")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ()
     */
    public function classes()
    {
        $school_id = $this->request->request('school_id');
        if (!$school_id) {
            $this->error('参数错误');
        }

        $listRows = $this->request->request('listRows', 10);
        $date_type = $this->request->request('date_type', 3);
        $keywords = $this->request->request('keywords', '');

        $search_classes = [];
        // 如果有 $keywords 先搜索出 classes 信息
        if ($keywords) {
            $search_classes = \app\common\model\Classes::alias('classes')
                ->join('__SCHOOL__ school', 'school.id = classes.school_id')
                ->join('__AREA__ area', 'area.id = school.city_id')
                ->join('__GRADE__ grade', 'grade.id = classes.grade_id')
                ->join('__CLASSROOM__ classroom', 'classroom.id = classes.classroom_id', 'left')
                ->join('__BUILDING__ building', 'building.id = classroom.building_id', 'left')
                ->join('__GARDEN__ garden', 'garden.id = building.garden_id', 'left')
                ->join('__TEACHER__ teacher', 'teacher.id = classes.headmaster', 'left')
                ->join('__USER__ user', 'user.id = teacher.user_id', 'left')
                ->where('classes.school_id', $school_id)
                ->whereLike('classes.name', "%$keywords%")
                ->column('classes.id,classes.name,classes.logo,classes.slogan,classes.grade_id,grade.name grade_name,classes.school_id,school.name school_name,school.logo school_logo,classes.classroom_id,classroom.name classroom_name,building.id building_id,building.name building_name,garden.id garden_id,garden.name garden_name,classes.headmaster,user.nickname headmaster_name,user.avatar headmaster_avatar,area.shortname city_name');

        }

        if ($keywords && !$search_classes) {
            $this->success('');
        }

        $date = get_time($date_type, true);

        $result = model\BehaviorRecord::alias('record')
            ->join('__BEHAVIOR_RECORD_DETAIL__ detail', 'detail.record_id = record.id')
            ->where('record.school_id', $school_id)
            ->where('record.created_at', '>=', $date['start_time'])
            ->where('record.created_at', '<=', $date['end_time'])
            ->whereIn('record.behavior_category_type', [model\BehaviorCategory::CLASSES,model\BehaviorCategory::DORM])
            ->whereIn('detail.behavior_category_type', [model\BehaviorCategory::CLASSES,model\BehaviorCategory::DORM_STUDENT])
            ->where('detail.class_id', '>', 0)
            ->where(function ($query) use ($search_classes) {
                if ($search_classes) {
                    $query->whereIn('detail.class_id', array_keys($search_classes));
                }
            })
            ->field('detail.class_id,sum(detail.score) score,record.json_data')
            ->group('detail.class_id')
            ->order('score', 'desc')
            ->paginate($listRows);

        if ($result) {
            if (!is_array($result)) $result = $result->toArray();

            if (isset($result['data']) && $result['data']) {

                if ($search_classes) {
                    foreach ($result['data'] as $key => $value) {
                        if (isset($search_classes[$value['class_id']])) {
                            $result['data'][$key] = array_merge($result['data'][$key], $search_classes[$value['class_id']]);
                        } else if ($value['json_data']) {
                            $result['data'][$key] = array_merge($result['data'][$key], $value['json_data']);
                        }
                        unset($result['data'][$key]['json_data']);
                        $count = model\BehaviorRecord::alias('record')
                            ->join('__BEHAVIOR_RECORD_DETAIL__ detail', 'detail.record_id = record.id')
                            ->where('record.school_id', $school_id)
                            ->where('record.created_at', '>=', $date['start_time'])
                            ->where('record.created_at', '<=', $date['end_time'])
                            ->whereIn('record.behavior_category_type', [model\BehaviorCategory::CLASSES,model\BehaviorCategory::DORM])
                            ->whereIn('detail.behavior_category_type', [model\BehaviorCategory::CLASSES,model\BehaviorCategory::DORM_STUDENT])->where('detail.class_id', '>', 0)
                            ->group('detail.class_id')
                            ->having('sum(score) > ' . $value['score'])
                            ->count();
                        $result['data'][$key]['sort'] = $count + 1;
                    }
                } else {
                    $class_ids = array_column($result['data'], 'class_id');
                    $classes = \app\common\model\Classes::alias('classes')
                        ->join('__SCHOOL__ school', 'school.id = classes.school_id')
                        ->join('__AREA__ area', 'area.id = school.city_id')
                        ->join('__GRADE__ grade', 'grade.id = classes.grade_id')
                        ->join('__CLASSROOM__ classroom', 'classroom.id = classes.classroom_id', 'left')
                        ->join('__BUILDING__ building', 'building.id = classroom.building_id', 'left')
                        ->join('__GARDEN__ garden', 'garden.id = building.garden_id', 'left')
                        ->join('__TEACHER__ teacher', 'teacher.id = classes.headmaster', 'left')
                        ->join('__USER__ user', 'user.id = teacher.user_id', 'left')
                        ->whereIn('classes.id', $class_ids)
                        ->column('classes.id,classes.name,classes.logo,classes.slogan,classes.grade_id,grade.name grade_name,classes.school_id,school.name school_name,school.logo school_logo,classes.classroom_id,classroom.name classroom_name,building.id building_id,building.name building_name,garden.id garden_id,garden.name garden_name,classes.headmaster,user.nickname headmaster_name,user.avatar headmaster_avatar,area.shortname city_name');

                    // 第一个是分数最大的
                    $max = current($result['data']);

                    // 获取比当前最大分分数高的人数
                    $count = model\BehaviorRecord::alias('record')
                        ->join('__BEHAVIOR_RECORD_DETAIL__ detail', 'detail.record_id = record.id')
                        ->where('record.school_id', $school_id)
                        ->where('record.created_at', '>=', $date['start_time'])
                        ->where('record.created_at', '<=', $date['end_time'])
                        ->whereIn('record.behavior_category_type', [model\BehaviorCategory::CLASSES,model\BehaviorCategory::DORM])
                        ->whereIn('detail.behavior_category_type', [model\BehaviorCategory::CLASSES,model\BehaviorCategory::DORM_STUDENT])->where('detail.class_id', '>', 0)
                        ->where('detail.class_id', '>', 0)
                        ->group('detail.class_id')
                        ->having('sum(score) > ' . $max['score'])
                        ->count();

                    foreach ($result['data'] as $key => $value) {
                        if (isset($classes[$value['class_id']])) {
                            $result['data'][$key] = array_merge($result['data'][$key], $classes[$value['class_id']]);
                        } else if ($value['json_data']) {
                            $result['data'][$key] = array_merge($result['data'][$key], $value['json_data']);
                        }
                        unset($result['data'][$key]['json_data']);

                        //数组中第一个是当前分数最高的 排名为$sort
                        if ($key == 0) {
                            $result['data'][$key]['sort'] = $count + $key + 1;
                        } else {
                            // 继续循环
                            // 如果当前的分数与上一个的相等 那么就与上一个的排名并列
                            if ($result['data'][$key - 1]['score'] == $value['score']) {
                                $result['data'][$key]['sort'] = $result['data'][$key - 1]['sort'];
                            } else {
                                // 如果不等 那就看看有没有分页情况
                                // 如果有分页 也就是说之前的所有的分数都大于当前的分数 排名累加上
                                $result['data'][$key]['sort'] = ($result['current_page'] - 1) * $listRows + $key + 1;
                            }
                        }
                    }
                }
            }
        }

        $this->success('', $result);

    }

    /**
     * @ApiTitle    (点评记录)
     * @ApiAuthor   (Zhenzh)
     * @ApiDate     (2020/6/29)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/ranking/records)
     * @ApiHeaders  (name="token", type="string", required=true, description="请求的Token")
     * @ApiParams   (name="id", type="int", required=true, description="id 学生id|宿舍id|班级id，根据type类型传不同的值", sample="")
     * @ApiParams   (name="type", type="string", required=true, description="类型 student=学生|dorm=宿舍|classes=班级", sample="student")
     * @ApiParams   (name="time_type", type="string|int", required=true, description="1|today=今天 2|yesterday=昨天 3|week=本周 4|lastweek=上周 5|day7=近7天 6|month=本月 7|lastmonth=上月 8|day30=近30天 9|quarter=本季度 10|lastquarter=上季度 11|year=本年 12|lastyear=上年 13|month1=近一个月 14|month3=近三个月", sample="")
     * @ApiParams   (name="page", type="int", required=false, description="页码", sample="")
     * @ApiParams   (name="listRows", type="int", required=false, description="每页条数", sample="")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ({
    "code": 1,
    "msg": "",
    "time": "1593396881",
    "data": {
    "total": 1,
    "per_page": 20,
    "current_page": 1,
    "last_page": 1,
    "data": [
    {
    "id": 646,
    "record_user_id": 372,
    "record_username": "20200318001",
    "record_user_group": "学生会",
    "behavior_category_type": 2,
    "comment": "",
    "created_at": 1593396587,
    "total_score": 2,
    "details": [
    {
    "id": 1138,
    "record_id": 646,
    "behavior_category_id": 22,
    "behavior_category_type": 2,
    "behavior_id": 89,
    "behavior_name": "干净整洁",
    "behavior_type": 1,
    "behavior_image_id": 38,
    "behavior_image_url": "/uploads/behavior/behavior38.png",
    "unit_score": 2,
    "count": 1,
    "score": 2,
    "is_deduct": 0,
    "comment": null,
    "bed_id": 0,
    "bed_num": 0,
    "class_id": 0,
    "student_id": 0,
    "category": {
    "id": 22,
    "name": "宿舍",
    "description": null,
    "sort": 1,
    "type": 2,
    "status": 1,
    "is_deduct": 1,
    "school_id": 36,
    "created_at": 1583717751,
    "deleted_at": null,
    "image": ""
    }
    }
    ],
    "images": []
    }
    ]
    }
    })
     */
    public function Records()
    {
        $id = $this->request->request('id');
        $type = $this->request->request('type');
        $time_type = $this->request->request('time_type');
        $listRows = $this->request->request('listRows');

        switch ($type) {
            case 'classes':
                $behavior_category_type = [BehaviorCategory::CLASSES, BehaviorCategory::STUDENT, BehaviorCategory::DORM_STUDENT];
                break;
            case 'student':
                $behavior_category_type = [BehaviorCategory::STUDENT, BehaviorCategory::DORM_STUDENT];
                break;
            case 'dorm':
                $behavior_category_type = [BehaviorCategory::DORM, BehaviorCategory::DORM_STUDENT];
                break;
            default:
                return $this->error('类型错误');
                break;
        }

        //$list = BehaviorRecord::getRecords($type, $id, $behavior_category_type, $time_type, $listRows);

        $date = get_time($time_type, true);

        if (!$listRows) {
            $listRows = config('paginate.list_rows');
        }

        $list = BehaviorRecord::alias('record')->with(['details' => function($query) use ($behavior_category_type,$type,$id){
            $query->with('category')->whereIn('behavior_category_type', $behavior_category_type);
            if ($type == 'classes') {
                $query->where('class_id', $id);
            } else if ($type == 'student') {
                $query->where('student_id', $id);
            }
        }, 'images'])
            ->join('__BEHAVIOR_RECORD_DETAIL__ detail', 'detail.record_id = record.id')
            ->where(function ($query) use ($type,$id) {
                if ($type == 'dorm') {
                    $query->where('record.dorm_id', $id);
                } else if ($type == 'classes') {
                    $query->where('detail.class_id', $id);
                } else if ($type == 'student') {
                    $query->where('detail.student_id', $id);
                }
            })
            ->whereIn('detail.behavior_category_type', $behavior_category_type)
            ->whereBetween('record.created_at', [$date['start_time'], $date['end_time']])
            ->field('record.id,record.record_user_id,record.record_username,record_user_group,record.behavior_category_type,record.comment,record.created_at')
            ->group('record.id')
            ->order('record.id', 'desc')
            ->paginate($listRows)
            ->toArray();

        $student_ids = [];
        foreach ($list['data'] as $key => $value) {
            $student_ids += array_column($value['details'], 'student_id');
            $list['data'][$key]['total_score'] = array_sum(array_column($value['details'], 'score'));
            if ($type == 'student') {
                $record_detail_ids = array_column($value['details'], 'id');
                foreach ($value['images'] as $k => $image) {
                    if (!in_array($image['record_detail_id'], $record_detail_ids)) {
                        unset($list['data'][$key]['images'][$k]);
                    }
                }
            }
        }

        $students = [];
        if ($student_ids) {
            $student_ids = array_unique($student_ids);
            $students = model\Student::whereIn('id', $student_ids)->column('id,name');
        }

        foreach ($list['data'] as $key => &$value) {
            foreach ($value['details'] as $k => &$detail) {
                if (isset($students[$detail['student_id']])) {
                    $detail['student_name'] = $students[$detail['student_id']];
                } else {
                    $detail['student_name'] = '';
                }
            }
        }

        if (isset($list['error'])) {
            $this->error($list['msg']);
        }

        $this->success('', $list);
    }

}
